package ar.edu.unq.leezsi.requestcycle;

import java.io.Serializable;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.unq.leezsi.core.Context;
import ar.edu.unq.leezsi.html.ComponentConfigurator;
import ar.edu.unq.leezsi.html.Page;
import ar.edu.unq.leezsi.utils.RandomUtils;
import ar.edu.unq.leezsi.utils.ResponseWriter;

public class RequestCycle implements Serializable {
	private static final long serialVersionUID = 7096333498058148839L;

	protected static String getNewSessionId() {
		return RandomUtils.getLongestId();
	}

	private final Context context;
	private Page<?> page;
	private String contextURI;

	public RequestCycle(Context context) {
		this.context = context;
	}

	protected void doChain(HttpServletRequest req, HttpServletResponse res,
			FilterChain chain) {
		try {
			chain.doFilter(req, res);

		} catch (Exception e) {
			new ResponseWriter(res).writeException(e);
		}
	}

	public void doFilter(HttpServletRequest req, HttpServletResponse res,
			FilterChain chain) {

		try {
			this.contextURI = req.getContextPath();
			if (this.isAsync(req)) {
				new AjaxDispatcher().resolve(req, res, this);
			} else {
				new HTTPDispatcher().resolve(req, res, chain, this);
			}
		} catch (Exception e) {
			new ResponseWriter(res).writeException(e);
		}
	}

	public Context getContext() {
		return this.context;
	}

	public String getContextURI() {
		return this.contextURI;
	}

	public Page<?> getPage() {
		return this.page;
	}

	private boolean isAsync(HttpServletRequest req) {
		return req.getRequestURI().startsWith("async/");

	}

	protected void setPage(Page<?> page) {
		this.page = page;
		new ComponentConfigurator(this.getContext()).configure(page);
	}

}
